package com.base;
 
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.Date;


public class DataBase {
	public static Connection conn() {
		Connection myconn = null;
		try {
			String url = "jdbc:mysql://127.0.0.1/msg?user=root&password=123456&useUnicode=true&characterEncoding=UTF-8";
			Class.forName("org.gjt.mm.mysql.Driver").newInstance();
			myconn = (Connection) DriverManager.getConnection(url);
			if (myconn != null) {
				System.out.println("connection is success!!!");
			}
		} catch (Exception e) {
			System.out.println("connection error is>>>>>" + e);
		}
		return myconn;
	}

	public static void close(Connection conn) {
		try {
			if (conn != null) {
				conn.close();
				System.out.println("closed");
			}
		} catch (Exception e) {
			System.out.println("conn not been closed!!!" + e);
		}
	}
	
	public static void close(PreparedStatement ps) {
		try {
			if (ps != null) {
				ps.close();
			}
		} catch (Exception e) {
			System.out.println("ps not been closed!!" + e);
		}
	}

	public Connection addMsg(String name, String title, String mail, String msg) {
		Connection conn = conn();

		try {
			String url = "insert into message value(?,?,?,?)";
			PreparedStatement ps = (PreparedStatement) conn
					.prepareStatement(url);
			ps.setString(1, getUTF8(name));
			ps.setString(2, getUTF8(title));
			ps.setString(3, getUTF8(mail));
			if (msg.length() < 1000) {
				ps.setString(4, getUTF8(msg));
			} else {
				System.out.println("too long");
			}
			ps.executeUpdate();
			close(ps);
		} catch (Exception e) {
			System.out.println("addMsg Error  is -----" + e);
		}
		close(conn);

		return conn;
	}

	public String str(String a, String b, String c, String d) {
		String aa = null;
		try {
			aa = getUTF8(a) + getUTF8(b) + getUTF8(c) + getUTF8(d);
			System.out.println(aa.toString());
		} catch (Exception e) {
			// TODO: handle exception
			e.getStackTrace();
		}

		return aa;
	}

	public String getUTF8(String name) throws UnsupportedEncodingException {
		if (name == null) {
			name = "";
		}
		return new String(name.getBytes("iso-8859-1"), "UTF-8");
	}

	public String getDate() {
		Date date = new Date();
		String mm = new Timestamp(date.getTime()).toString();
		System.out.println(mm);
		return mm;
	}

	public ResultSet resultset() {
		ResultSet rs = null;
		Connection conn = conn();
		try {
			String url = "select * from message";
			PreparedStatement ps = (PreparedStatement) conn
					.prepareStatement(url);
			rs = (ResultSet) ps.executeQuery();
		} catch (Exception e) {
			System.out.println("get result error" + e);
		}
		return rs;
	}

	public static void main(String args[]) {
		DataBase db = new DataBase();
		db.getDate();
	}

}
